package com.hsogoo.avatar.demo.handler;

import com.google.gson.Gson;
import com.hsogoo.avatar.model.AvatarRequest;
import com.hsogoo.avatar.model.AvatarResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @Author huangsaigang
 * Created @2018/10/1.
 */
public class DemoServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server get message : " + msg);
        AvatarRequest request = new Gson().fromJson(msg.toString(), AvatarRequest.class);
        AvatarResponse response = new AvatarResponse();
        response.setRequestId(request.getRequestId());
        response.setResult("result");
        ctx.channel().writeAndFlush(new Gson().toJson(response));
        ctx.channel().writeAndFlush("\r\n");
    }

//    @Override
//    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
//        if(evt instanceof IdleStateEvent){
//            IdleStateEvent event = (IdleStateEvent)evt;
//            if(event.state().equals(IdleState.READER_IDLE)){
//                System.out.println("读空闲");
//                ctx.channel().close();
//            }else if(event.state().equals(IdleState.WRITER_IDLE)){
//                System.out.println("写空闲");
//            }else if(event.state().equals(IdleState.ALL_IDLE)){
//                System.out.println("读写空闲");
//                ctx.channel().writeAndFlush("ping\r\n");
//            }
//        }
//    }
}
